from django.contrib.auth.hashers import check_password
from django.core.paginator import Paginator
from django.shortcuts import render
from .serializer import UserSerializer,NewsSerializer,CommentSerializer

# Create your views here.
from .models import User,News
from django.views import View
from rest_framework.response import Response
from rest_framework.views import APIView
class LoginView(APIView):
    def post(self, request):
        print(request.data)
        username = request.data.get('username')
        user_obj = User.objects.filter(username=username).first()
        if user_obj:
            return Response({'msg':'ok','code':200, 'user_id': user_obj.pk, 'username': username})
        else:
            return Response({'msg': '用户不正确', 'code': 400})
    def get(self,request):
        list = User.objects.all()
        ser = UserSerializer(list,many=True)
        return Response(ser.data)
class NewsM(APIView):
    def get(self, request):
        current_page = request.query_params.get('current_page')
        goods_list = News.objects.all()
        paginotor = Paginator(goods_list, 1)
        pated = paginotor.page(current_page)
        goods_serializer = NewsSerializer(pated, many=True)
        return Response({
            'data': goods_serializer.data,
            'page_list': [i for i in paginotor.page_range],
            'page_sum': paginotor.num_pages
        })

class AddCommitView(APIView):
    def post(self,request):
        print(request.data)
        user = request.data.get('user')
        user_obj = User.objects.filter(username=user).first()
        commit_list = CommentSerializer(data=request.data)
        if commit_list.is_valid():
            commit_list.save()
            if user_obj.user_level == 1:
                user_obj.score+=10
                user_obj.save()
            else:
                user_obj.score+=20
                user_obj.save()
            return Response({'msg':'添加成功',"code":200})
        else:
            return  Response({'error':commit_list.errors})


